/**
 * 首页JS文件 - 负责主页面内容加载和展示
 */

document.addEventListener('DOMContentLoaded', () => {
    // 获取主要DOM元素
    const statsContainer = document.getElementById('stats-container');
    const hotTopicsContainer = document.getElementById('hot-topics-container');
    const latestNewsContainer = document.getElementById('latest-news-container');
    const popularPapersContainer = document.getElementById('popular-papers-container');
    const companyActivityContainer = document.getElementById('company-activity-container');

    // 初始化页面数据
    initPage();

    /**
     * 初始化页面，加载所有数据
     */
    async function initPage() {
        try {
            // 并行加载所有数据
            await Promise.all([
                loadStats(),
                loadHotTopics(),
                loadLatestNews(),
                loadPopularPapers(),
                loadCompanyActivity()
            ]);
        } catch (error) {
            console.error('初始化页面失败:', error);
        }
    }

    /**
     * 加载统计数据
     */
    async function loadStats() {
        if (!statsContainer) return;
        
        App.showLoading(statsContainer);
        
        try {
            const data = await App.fetchAPI(App.API_ENDPOINTS.STATS);
            
            // 创建统计卡片
            const statsHtml = `
                <div class="row">
                    <div class="col-md-3 col-sm-6 mb-4">
                        <div class="stat-card">
                            <div class="stat-icon"><i class="fas fa-newspaper"></i></div>
                            <div class="stat-content">
                                <h3>${App.formatNumber(data.news_count)}</h3>
                                <p>新闻文章</p>
                                <span class="change ${data.news_trend >= 0 ? 'positive' : 'negative'}">
                                    ${App.calculatePercentChange(data.news_count, data.news_count_previous)}
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3 col-sm-6 mb-4">
                        <div class="stat-card">
                            <div class="stat-icon"><i class="fas fa-file-alt"></i></div>
                            <div class="stat-content">
                                <h3>${App.formatNumber(data.papers_count)}</h3>
                                <p>研究论文</p>
                                <span class="change ${data.papers_trend >= 0 ? 'positive' : 'negative'}">
                                    ${App.calculatePercentChange(data.papers_count, data.papers_count_previous)}
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3 col-sm-6 mb-4">
                        <div class="stat-card">
                            <div class="stat-icon"><i class="fas fa-building"></i></div>
                            <div class="stat-content">
                                <h3>${App.formatNumber(data.companies_count)}</h3>
                                <p>相关企业</p>
                                <span class="change ${data.companies_trend >= 0 ? 'positive' : 'negative'}">
                                    ${App.calculatePercentChange(data.companies_count, data.companies_count_previous)}
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3 col-sm-6 mb-4">
                        <div class="stat-card">
                            <div class="stat-icon"><i class="fas fa-tags"></i></div>
                            <div class="stat-content">
                                <h3>${App.formatNumber(data.topics_count)}</h3>
                                <p>热门话题</p>
                                <span class="change ${data.topics_trend >= 0 ? 'positive' : 'negative'}">
                                    ${App.calculatePercentChange(data.topics_count, data.topics_count_previous)}
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            statsContainer.innerHTML = statsHtml;
        } catch (error) {
            App.showError(statsContainer);
        }
    }

    /**
     * 加载热门话题
     */
    async function loadHotTopics() {
        if (!hotTopicsContainer) return;
        
        App.showLoading(hotTopicsContainer);
        
        try {
            const data = await App.fetchAPI(App.API_ENDPOINTS.HOT_TOPICS);
            
            let topicsHtml = '<div class="row">';
            
            data.topics.slice(0, 6).forEach(topic => {
                topicsHtml += `
                    <div class="col-md-4 col-sm-6 mb-4">
                        <div class="topic-card">
                            <h4>${topic.name}</h4>
                            <div class="topic-stats">
                                <span><i class="fas fa-newspaper"></i> ${topic.news_count}</span>
                                <span><i class="fas fa-file-alt"></i> ${topic.papers_count}</span>
                            </div>
                            <p>${topic.description}</p>
                            <div class="topic-trend ${topic.trend >= 0 ? 'positive' : 'negative'}">
                                <i class="fas ${topic.trend >= 0 ? 'fa-arrow-up' : 'fa-arrow-down'}"></i>
                                ${Math.abs(topic.trend)}%
                            </div>
                            <a href="/topics/${topic.id}" class="btn btn-outline-primary btn-sm">查看详情</a>
                        </div>
                    </div>
                `;
            });
            
            topicsHtml += '</div>';
            
            if (data.topics.length > 6) {
                topicsHtml += `
                    <div class="text-center mt-3">
                        <a href="/topics" class="btn btn-primary">查看更多话题</a>
                    </div>
                `;
            }
            
            hotTopicsContainer.innerHTML = topicsHtml;
        } catch (error) {
            App.showError(hotTopicsContainer);
        }
    }

    /**
     * 加载最新新闻
     */
    async function loadLatestNews() {
        if (!latestNewsContainer) return;
        
        App.showLoading(latestNewsContainer);
        
        try {
            const data = await App.fetchAPI(App.API_ENDPOINTS.LATEST_NEWS);
            
            let newsHtml = '<div class="row">';
            
            data.news.slice(0, 6).forEach(news => {
                const date = App.formatDate(news.published_date);
                
                // 创建标签HTML
                let tagsHtml = '';
                if (news.tags && news.tags.length > 0) {
                    tagsHtml = news.tags.slice(0, 3).map(tag => 
                        `<span class="badge bg-secondary">${tag}</span>`
                    ).join(' ');
                }
                
                newsHtml += `
                    <div class="col-md-4 col-sm-6 mb-4">
                        <div class="card h-100">
                            <div class="card-body">
                                <div class="source-date">
                                    <span class="source">${news.source}</span>
                                    <span class="date">${date}</span>
                                </div>
                                <h5 class="card-title">${news.title}</h5>
                                <p class="card-text">${news.summary}</p>
                                <div class="tags mb-2">
                                    ${tagsHtml}
                                </div>
                            </div>
                            <div class="card-footer">
                                <a href="${news.url}" target="_blank" class="btn btn-sm btn-outline-primary">阅读原文</a>
                                <a href="/news/${news.id}" class="btn btn-sm btn-link">详情</a>
                            </div>
                        </div>
                    </div>
                `;
            });
            
            newsHtml += '</div>';
            
            if (data.news.length > 6) {
                newsHtml += `
                    <div class="text-center mt-3">
                        <a href="/news" class="btn btn-primary">查看更多新闻</a>
                    </div>
                `;
            }
            
            latestNewsContainer.innerHTML = newsHtml;
        } catch (error) {
            App.showError(latestNewsContainer);
        }
    }

    /**
     * 加载热门论文
     */
    async function loadPopularPapers() {
        if (!popularPapersContainer) return;
        
        App.showLoading(popularPapersContainer);
        
        try {
            const data = await App.fetchAPI(App.API_ENDPOINTS.POPULAR_PAPERS);
            
            let papersHtml = '<div class="list-group">';
            
            data.papers.slice(0, 5).forEach(paper => {
                const date = App.formatDate(paper.published_date);
                
                papersHtml += `
                    <div class="list-item">
                        <div class="list-item-header">
                            <h5><a href="/papers/${paper.id}">${paper.title}</a></h5>
                            <span class="date">${date}</span>
                        </div>
                        <div class="authors">${paper.authors.join(', ')}</div>
                        <p>${paper.abstract}</p>
                        <div class="list-item-footer">
                            <div class="metrics">
                                <span><i class="fas fa-eye"></i> ${paper.views}</span>
                                <span><i class="fas fa-download"></i> ${paper.downloads}</span>
                                <span><i class="fas fa-quote-right"></i> ${paper.citations}</span>
                            </div>
                            <a href="${paper.url}" target="_blank" class="btn btn-sm btn-outline-primary">查看原文</a>
                        </div>
                    </div>
                `;
            });
            
            papersHtml += '</div>';
            
            if (data.papers.length > 5) {
                papersHtml += `
                    <div class="text-center mt-3">
                        <a href="/papers" class="btn btn-primary">查看更多论文</a>
                    </div>
                `;
            }
            
            popularPapersContainer.innerHTML = papersHtml;
        } catch (error) {
            App.showError(popularPapersContainer);
        }
    }

    /**
     * 加载企业活动
     */
    async function loadCompanyActivity() {
        if (!companyActivityContainer) return;
        
        App.showLoading(companyActivityContainer);
        
        try {
            const data = await App.fetchAPI(App.API_ENDPOINTS.COMPANY_ACTIVITY);
            
            let companiesHtml = '<div class="row">';
            
            data.companies.slice(0, 4).forEach(company => {
                let activityListHtml = '';
                
                if (company.recent_activities && company.recent_activities.length > 0) {
                    activityListHtml = '<ul class="activity-list">';
                    company.recent_activities.slice(0, 3).forEach(activity => {
                        const date = App.formatDate(activity.date);
                        activityListHtml += `
                            <li>
                                <span class="activity-date">${date}</span>
                                <span class="activity-text">${activity.description}</span>
                            </li>
                        `;
                    });
                    activityListHtml += '</ul>';
                }
                
                companiesHtml += `
                    <div class="col-md-6 mb-4">
                        <div class="company-card">
                            <div class="company-header">
                                <h4>${company.name}</h4>
                                <span class="company-type">${company.type}</span>
                            </div>
                            <p>${company.description}</p>
                            <div class="activity-section">
                                <h5>最近活动</h5>
                                ${activityListHtml || '<p>暂无最近活动</p>'}
                            </div>
                            <a href="/companies/${company.id}" class="btn btn-outline-primary btn-sm">公司详情</a>
                        </div>
                    </div>
                `;
            });
            
            companiesHtml += '</div>';
            
            if (data.companies.length > 4) {
                companiesHtml += `
                    <div class="text-center mt-3">
                        <a href="/companies" class="btn btn-primary">查看更多企业</a>
                    </div>
                `;
            }
            
            companyActivityContainer.innerHTML = companiesHtml;
        } catch (error) {
            App.showError(companyActivityContainer);
        }
    }
}); 